package com.wxapp.admin.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wxapp.admin.api.pojo.entity.RoleDO;
import com.wxapp.admin.api.pojo.entity.UserRoleDO;
import com.wxapp.admin.api.pojo.vo.roleUser.QRoleUserSaveVo;
import com.wxapp.admin.service.mapper.RoleMapper;
import com.wxapp.admin.service.mapper.UserMapper;
import com.wxapp.admin.service.mapper.UserRoleMapper;
import com.wxapp.admin.service.service.UserRoleService;
import com.wxapp.common.constant.base.IBaseService;
import com.wxapp.common.constant.pojo.vm.PSimpleListVm;
import com.wxapp.common.constant.pojo.vm.ResultVm;
import com.wxapp.common.constant.pojo.vo.UserVo;
import com.wxapp.common.util.check.CheckUtil;
import com.wxapp.common.util.copy.CopyUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lgl
 * @Description 用户部门关联
 * @Datetime 2022/8/6 17:03
 * @Modified By
 */
@Service
@RequiredArgsConstructor
public class UserRoleServiceImpl extends IBaseService implements UserRoleService {
    private final UserRoleMapper userRoleMapper;
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    @Override
    public ResultVm<String> addUserRole(UserVo userVo, QRoleUserSaveVo qRoleUserSaveVo) {
        var user = userMapper.selectById(qRoleUserSaveVo.getUserId());
        if (CheckUtil.isNullObject(user)) {
            return error("找不到用户信息");
        }
        LambdaUpdateWrapper<UserRoleDO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.in(UserRoleDO::getUserId, qRoleUserSaveVo.getUserId()).eq(UserRoleDO::getStatus, true);
        userRoleMapper.delete(wrapper);
        List<UserRoleDO> list = new ArrayList<>();
        qRoleUserSaveVo.getRoleId().forEach(s -> {
            UserRoleDO userRoleDO = new UserRoleDO();
            userRoleDO.setRoleId(s);
            userRoleDO.setUserId(qRoleUserSaveVo.getUserId());
            userRoleDO.setCreateBy(userVo.getId());
            list.add(userRoleDO);
        });
        userRoleMapper.insertBatch(list);
        return success("添加角色成功");
    }

    @Override
    public ResultVm<List<PSimpleListVm>> bindRole() {
        LambdaQueryWrapper<UserRoleDO> userRole = new LambdaQueryWrapper<>();
        userRole.eq(UserRoleDO::getStatus, true);
        LambdaQueryWrapper<RoleDO> role = new LambdaQueryWrapper<>();
        role.select(RoleDO::getId, RoleDO::getRoleName);
        role.eq(RoleDO::getStatus, true);
        var roleDOS1 = roleMapper.selectList(role);
        return success(CopyUtil.copyListNew(roleDOS1, PSimpleListVm::new, (s, r) -> {
            r.setName(s.getRoleName());
            return null;
        }));
    }
}
